import config from "./WebIMConfig";
import websdk from "easemob-websdk";
import emedia from "easemob-emedia";
import webrtc from "easemob-webrtc";
import {getToken, getImToken} from '@/utils/auth'
import {Message} from "element-ui";
import store from "@/store";
import {GetPreList} from "@/api/prescribe";

function ack(message) {
	let bodyId = message.id; // 需要发送已读回执的消息id
	let msg = new WebIM.message("read", WebIM.conn.getUniqueId());
	msg.set({
		id: bodyId,
		to: message.from
	});
	WebIM.conn.send(msg.body);
}

// 初始化IM SDK
let conn = {};
WebIM.config = config;
conn = WebIM.conn = new WebIM.connection({
	appKey: WebIM.config.appkey,
	isHttpDNS: WebIM.config.isHttpDNS,
	isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
	https: WebIM.config.https,
	url: WebIM.config.socketServer,
	apiUrl: WebIM.config.restServer,
	isAutoLogin: WebIM.config.isAutoLogin,
	heartBeatWait: WebIM.config.heartBeatWait,
	autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
	autoReconnectInterval: WebIM.config.autoReconnectInterval,
	delivery: WebIM.config.delivery,
	useOwnUploadFun: WebIM.config.useOwnUploadFun
})

// 注册监听回调
WebIM.conn.listen({
	onOpened: function (message) {
		console.log(getImToken())
	}, // 连接成功回调
	onClosed: function (message) {
		console.log('您已成功退出环信')
	}, // 连接关闭回调
	onTextMessage: function (message) {
		console.log('收到消息', message)
		if(message.ext) {
			/*setTimeout(() => {
				GetMessage({orderId: message.ext.orderId}).then(res => {
					for (let i = 0; i < res.data.length; i++) {
						if (res.data[i].type === 'PRE') {
							GetPreList({prescribeId: res.data[i].message}).then(response => {
								Vue.set(res.data[i], 'prescribe', response.data);
							})
						}
					}
					store.commit('setMessageList', res.data);
				})
			}, 1500)*/
			let obj = {};
			obj.receiver = message.to;
			obj.sender = message.from;
			if(message.ext.isPrescribe) {
				GetPreList({prescribeId: message.data}).then(response => {
					obj.prescribe = response.data;
					obj.message = message.data;
					obj.type = 'PRE';
					store.commit('pushMessageList', obj);
				})
			} else if(message.contentsType == 'IMAGE') {
				obj.message = message.url;
				obj.type = 'IMG';
				store.commit('pushMessageList', obj);
			} else {
				obj.message = message.data;
				if(message.ext.type == 'SYS') {
					obj.type = message.ext.type;
					store.commit('setPreStatus', message.ext.preId)
				} else {
					obj.type = 'TXT';
				}
				store.commit('pushMessageList', obj);
			}
		}
		//setUnreadMsg(message)
	}, // 收到文本消息
	onEmojiMessage: function (message) {

	}, // 收到表情消息
	onPictureMessage: function (message) {
		console.log(message)
		if(message.ext) {
			let obj = {};
			obj.receiver = message.to;
			obj.sender = message.from;
			obj.message = message.url;
			obj.type = 'IMG';
			store.commit('pushMessageList', obj);
			/*setTimeout(() => {
				GetMessage({orderId: message.ext.orderId}).then(res => {
					store.commit('setMessageList', res.data);
				})
			}, 500)*/
		}
	}, // 收到图片消息
	onCmdMessage: function (message) {

	}, // 收到命令消息
	onAudioMessage: function (message) {

	}, // 收到音频消息
	onLocationMessage: function (message) {

	}, // 收到位置消息
	onFileMessage: function (message) {
		console.log(message)
		//setUnreadMsg(message)
	}, // 收到文件消息
	onVideoMessage: function (message) {

	}, // 收到视频消息
	onPresence: function (message) {

	}, // 处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
	onRoster: function (message) {

	}, // 处理好友申请
	onInviteMessage: function (message) {

	}, // 处理群组邀请
	onOnline: function () {
		// console.log("onOnline 网络已连接");
	}, // 本机网络连接成功
	onOffline: function () {
		// console.log("onOffline 网络已断开");
	}, // 本机网络掉线
	onError: function (message) {
		let userId = JSON.parse(localStorage.getItem("userInfo")).userId;
		if(userId !== 1) {
			if(getToken()) {
				console.log(message)
				if (message.type == 0) {
					console.log('请输入账号密码')
				} else if (message.type == 28) {
					console.log("未登陆")
				} else if (message.data && JSON.parse(message.data.data).error_description == "user not found") {
					Message.error("用户名不存在！")
				} else if (message.data && JSON.parse(message.data.data).error_description == "invalid password") {
					console.log('密码无效！')
				} else if (message.data && JSON.parse(message.data.data).error_description == "user not activated") {
					Message.error("用户已被封禁！")
				} else if (message.type == "504") {
					Message("消息撤回失败");
				}
			}
		}
		// 报错返回到登录页面
		// Vue.$router.push({ path: '/login' });
	}, // 失败回调
	onRecallMessage: message => {

	},
	onBlacklistUpdate: function (list) { // 黑名单变动

	},
	onReceivedMessage: function (message) {
	}, // 收到消息送达服务器回执

	onDeliveredMessage: function (message) {

	}, // 收到消息送达客户端回执

	onReadMessage: function (message) {

	}, // 收到消息已读回执

	onCreateGroup: function (message) {

	}, // 创建群组成功回执（需调用createGroupNew）
	onMutedMessage: function (message) {

	} // 如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
});

emedia.config({
	restPrefix: 'https://a1.easemob.com', //配置服务器域名、必填 比如: 'https://a1-hsb.easemob.com'
	appkey: WebIM.config.appkey           // 配置appkey、必填
});

//有人加入会议，其他人调用joinXX等方法，如果加入成功，已经在会议中的人将会收到
emedia.mgr.onMemberJoined = function (member) {
	window.clearTimeout(store.getters.timer);
	store.commit('setTimer', undefined);
	console.log('>>>>>', member.name, ' 加入会议')
};

//有人退出会议
emedia.mgr.onMemberExited = function (member) {
	console.log('>>>>>', member.name, ' 退出会议')
};

// 当远端流加入频道时，会触发 emedia.mgr.onStreamAdded 方法，我们需要给 emedia.mgr 赋值 onStreamAdded 用来接收 stream
emedia.mgr.onStreamAdded = function(member, stream) {
	// member：发布流人员的信息、stream：流信息
	if(!stream.located()) {
		let option = {
			member: member,
			stream: stream,
			subVideo: true,
			subAudio: true,
			videoTag: document.querySelector('#video')
		}
		emedia.mgr.subscribe(option.member, option.stream, option.subVideo, option.subAudio, option.videoTag)
		store.commit('setPushedStream', true);
	}
}

// 当远端流被移除时（例如远端用户调用了 Stream.unpublish）， 停止订阅该流并移除它的画面
emedia.mgr.onStreamRemoved = function(member, stream) {
	// member：发布流人员的信息、stream：流信息
	if(store.getters.pushedStream) {
		store.commit('setConfrId', undefined);
		store.commit('setPushedStream', false);
		emedia.mgr.exitConference()
		if(stream.located() == false) {
			console.log("远程停止发布流>>>>>>>>>>>>>>>")
			emedia.mgr.unsubscribe(stream); // 停止订阅流
			window.confirmCallback();
		}
	}
}

//会议退出；自己主动退 或 服务端主动关闭；
emedia.mgr.onConferenceExit = function (reason, failed) {
	reason = (reason || 0);
	switch (reason){
		case 0:
			reason = "正常挂断";
			return;
		case 1:
			reason = "没响应";
			break;
		case 2:
			reason = "服务器拒绝";
			break;
		case 3:
			reason = "对方忙";
			break;
		case 4:
			reason = "失败,可能是网络或服务器拒绝";
			if(failed === -9527){
				reason = "失败,网络原因";
			}
			if(failed === -500){
				reason = "Ticket失效";
			}
			if(failed === -502){
				reason = "Ticket过期";
			}
			if(failed === -504){
				reason = "链接已失效";
			}
			if(failed === -508){
				reason = "会议无效";
			}
			if(failed === -510){
				reason = "服务端限制";
			}
			break;
		case 5:
			reason = "不支持";
			break;
		case 10:
			reason = "其他设备登录";
			break;
		case 11:
			reason = "会议关闭";
			break;
	}
	Message(reason);
};

WebIM.WebRTC = webrtc;
WebIM.EMedia = emedia;
export default WebIM;
